<?php
class BaseAction extends Action
{


    /* 调用不存在的方法时，自动加载
	 *
	 */
	public function __call($func, $args)
	{
		$class_name = get_called_class();
		$err_msg = $func . '() does not exist.';

		if(APP_DEBUG)
		{
			$err_msg = $class_name . ':' . $err_msg;
			halt($err_msg);
		}
		else
		{
			echo $err_msg;
		}

		die();
	}


    /* 默认首页
	 *
	 */
	public function index()
	{
		echo "Welcome!";
	}


    /* 保存日志（调试用）
	 *
	 */
	public function save_log($custom='')
	{
		$db_conf = $this->get_db_config();

		$data['get'] = json_encode($_GET);
		$data['post'] = json_encode($_POST);
		if($custom != NULL)
		{
			$data['custom'] = $custom;
		}
		$res = M('log', '', $db_conf)->add($data);
	}


    /* 获取密码的秘钥
     *
     */
    public function get_password_secret_key($username)
    {
        $pwd_secret_key_tmp = strtoupper( md5($username) );
        $pwd_secret_key = substr($pwd_secret_key_tmp, 12, 8);
        return $pwd_secret_key;
    }


    /* 密码加密算法
	 * password：明文密码；secret_key：秘钥
	 */
	public function get_md5_password($password, $secret_key)
	{
        $true_password = md5( md5($password) . $secret_key );
		return $true_password;
	}


    /* 组装数据库配置信息（用于跨库操作）
	 * db_name：数据库名，若为空则默认为主库；为original则默认为本地服务器
	 */
	public function get_db_config($db_name='')
	{
        // 数据库配置字段
        $db_conf_arr = array(
            C('db_type'),
            '://',
            C('db_user'),
            ':',
            C('db_pwd'),
            '@',
            C('db_host'),
            ':',
            C('db_port'),
            '/'
        );
        // 获取原始配置
        $original_db_conf = implode('', $db_conf_arr);
        // 获取最终配置
        if($db_name)
		{
			// 检测数据库名是否包含非法字符
			$check_city_name = preg_match_all('/^[a-zA-Z]+$/', $db_name);
			if($check_city_name)
			{
				if($db_name == 'original')
                {
                    $db_conf = $original_db_conf;
                }
                else
                {
                    $db_conf = $original_db_conf . C('db_prefix') . $db_name;
                }
			}
			else
			{
				$db_conf = $original_db_conf . C('db_name');
			}
		}
		else
		{
			$db_conf = $original_db_conf . C('db_name');
		}
		return $db_conf;
	}


	/* 分页
	 * $count：总条数
	 * $page_size：分页尺寸
	 * $button_amount：按钮个数
	 * $page_button_parm：页数按钮的附加参数（数组，采用'参数名'=>'参数值'的格式）
	 */
	public function page($count, $page_size=20, $button_amount=5, $page_button_parm=array())
	{
		// 存储总条数
		$PAGE['count'] = $count;
		// 计算总页数
		$PAGE['total_page'] = intval( ceil($PAGE['count'] / $page_size) );
		if($PAGE['total_page'] < 1)
		{
			$PAGE['total_page'] = 1;
		}
		// 获取当前页数
		$PAGE['now_page'] = intval($_GET['now_page']);
		if($PAGE['now_page'] <= 0)
		{
			$PAGE['now_page'] = 1;
		}
		if($PAGE['now_page'] > $PAGE['total_page'])
		{
			$PAGE['now_page'] = $PAGE['total_page'];
		}
		// 计算“上一页”页数
		$PAGE['prev_page'] = $PAGE['now_page'] - 1;
		if($PAGE['prev_page'] <= 0)
		{
			$PAGE['prev_page'] = 'disable';
		}
		// 计算“下一页”页数
		$PAGE['next_page'] = $PAGE['now_page'] + 1;
		if($PAGE['next_page'] > $PAGE['total_page'])
		{
			$PAGE['next_page'] = 'disable';
		}
		// 首页页码
		$PAGE['first_page'] = 1;
		// 末页页码
		$PAGE['end_page'] = $PAGE['total_page'];
		// 计算要显示的页数
		$show_pages[] = $PAGE['now_page'];
		for($i=1; $i<=$PAGE['end_page']; $i++)
		{
			$tmp = $PAGE['now_page'] + $i;
			if( ($tmp >= $PAGE['first_page']) && ($tmp <= $PAGE['end_page']) )
			{
				$show_pages[] = $tmp;
			}
			$tmp = $PAGE['now_page'] - $i;
			if( ($tmp >= $PAGE['first_page']) && ($tmp <= $PAGE['end_page']) )
			{
				$show_pages[] = $tmp;
			}
			if( count($show_pages) >= $button_amount )
			{
				break;
			}
		}
		sort($show_pages);
		if( count($show_pages) > $button_amount)
		{
			unset($show_pages[0]);
			$show_pages = array_values($show_pages);
		}
		$PAGE['page_button'] = $show_pages;
		// 计算查询范围
		$PAGE['limit'] = ($PAGE['now_page'] - 1) * $page_size . ',' . $page_size;
		// 处理附加参数
		if( $page_button_parm && is_array($page_button_parm) )
		{
			// 循环处理数据
			foreach($page_button_parm as $m=>$n)
			{
				// 循环拼装参数字符串
				$PAGE['page_button_prm'] .= $m . '=' . $n . '&';
				// 生成跳页表单的隐藏数据
				$tmp = array(
					'field_name' => $m,
					'field_value' => $n
				);
				$PAGE['page_button_hidden_parm'][] = $tmp;
			}
		}

		return $PAGE;
	}


    /* 输出信息至浏览器
     *
     */
    public function show_msg($msg_type, $msg='', $wait_second=1)
    {
        // 获取消息类型
        $msg_type = strval( trim($msg_type) );
        // 检查消息类型
        switch($msg_type)
        {
            case 'success':
                $text_color = 'green';
                break;
            case 'error':
                $text_color = 'red';
                break;
            default:
                return 0;
                die();
        }
        // 获取消息内容
        $msg = strval( trim($msg) );
        // 获取等待秒数
        $wait_second = intval($wait_second);
        // 组装消息
        $msg = '<span style="font-size:14px;font-weight:bold;color:' . $text_color . ';">' . $msg . '</span><br /><br />';
        // 输出消息
        echo $msg;
        sleep($wait_second);
        ob_flush();
        flush();
    }


    /* 检查登录
     *
     */
    public function check_login()
    {
        if($_SESSION['rmt_user'])
		{
            return 1;
		}
        if($_SESSION['install'])
		{
            return 2;
		}

        return 0;
    }


    /* 获取用户权限
     *
     */
    public function get_user_power()
    {
		// 安装
		if($_SESSION['install'])
        {
            return $_SESSION['install'];
        }
		// 受邀请注册
		if($_SESSION['invited'])
        {
            return $_SESSION['invited'];
        }

		return $_SESSION['rmt_user']['power'];
    }


    /* 公共头部
     *
     */
    public function head()
    {
        // 检查登录
        $check_login = $this->check_login();
        $this->assign('check_login', $check_login);
    }


	/* 检查是否开启MySQL事件调度器
	 *
	 */
	public function check_event_scheduler()
	{
		$db_conf_host = $this->get_db_config('original');

		$query = "SHOW VARIABLES LIKE 'event_scheduler'";
		$check_event_scheduler = M('', '', $db_conf_host)->query($query);
		if($check_event_scheduler[0]['Variable_name'] == 'event_scheduler' && $check_event_scheduler[0]['Value'] != 'ON')
		{
			return 0;
		}
		return 1;
	}


}
